﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using SharePointOptimizer.Model;
using Microsoft.Win32;
using System.IO;
using System.Text.RegularExpressions;
using SharePointOptimizer.SQLServer;
using System.Configuration;
using SharePointOptimizer.PL.WPF;
using WinInterop = System.Windows.Interop;
using System.ComponentModel;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using System.Runtime.InteropServices;
using System.Windows.Controls.Primitives;
using System.Threading;
using AG.Utilities;
using Microsoft.Windows.Controls;
using System.Security.Principal;
using SharePointOptimizer.DL.SQLServer;


namespace SharePointOptimizer.PL.WPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    /// 

    public partial class MainWindow : Window
    {

        public ObservableCollection<IssueServer> issueServers = new ObservableCollection<IssueServer>();
 
        // public static string strselectedSQLInstance = null;
        public bool traceRefreshSender = false;
        public bool stateOnline;
        public string INt;
        private bool isRunning = false;
        private DispatcherTimer TraceStatusCheckTimer = new DispatcherTimer(DispatcherPriority.Normal);

        SharePointOptimizerDataContext dc = new SharePointOptimizerDataContext(System.Configuration.ConfigurationManager.AppSettings.Get("ConnectionStringSSHCDatabase"));

        ICollectionView view;
        public MainWindow()
        {
            this.InitializeComponent();
            this.Loaded += new RoutedEventHandler(win_Loaded);
            this.SourceInitialized += new EventHandler(win_SourceInitialized);
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
            this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Help, HelpExecuted, HelpCanExecute));


            worker = new DataCollectionWorker(this);
            worker.ProgressUpdate += new ProgressUpdateEvent(worker_ProgressUpdate);
            worker.ProccessCompleted += new ProccesCompleted(worker_ProccessCompleted);
            worker.Completed += worker_Completed;
            worker.Cancelled += worker_Cancelled;
            worker.Failed += WorkFailed;

        
        }

        private DataCollectionWorker worker;


        public bool IsAdminRole()
        {
            AppDomain domain = Thread.GetDomain();

            domain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            WindowsPrincipal principle = (WindowsPrincipal)Thread.CurrentPrincipal;
            return principle.IsInRole(WindowsBuiltInRole.Administrator);
        }



        public static bool IsDatabaseCreated()
        {
            string DatabaseCreated = System.Configuration.ConfigurationManager.AppSettings.Get("DatabaseCreated");

            return DatabaseCreated == "true";
        }



        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Configuration.Configuration oConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                Logger.LogErrors = bool.Parse( oConfig.AppSettings.Settings["LogErrors"].Value.ToLower());
                Logger.LogDebugInfo = bool.Parse(oConfig.AppSettings.Settings["LogDebugInfo"].Value.ToLower());
                Logger.Initialize(System.Windows.Forms.Application.StartupPath);

                string DatabaseCreated = "";

                DatabaseCreated = oConfig.AppSettings.Settings["DatabaseCreated"].Value;

                if (!IsAdminRole())
                {
                    MessageBox.Show("The SharePoint Optimizer needs to be run as Administrator to use all the functionality.");
                }

                Licensing.Edition = Licensing.GetProductEdition(typeof(MainWindow).Assembly);

                SetVisibilityByProductEdition();

                if (DatabaseCreated.ToLower() == "false")
                {
                  
                    //Calls the New Database Setup window if the INstance is still set to Local
                    var DatabaseSetupWindow = new DatabaseSetup();
                    DatabaseSetupWindow.Show();
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

        }

        public void SetVisibilityByProductEdition()
        {
            if (Licensing.Edition == ProductEdition.Basic)
            {
            }
            else
            {
            }

        }

        void win_SourceInitialized(object sender, EventArgs e)
        {
            try
            {
                System.IntPtr handle = (new WinInterop.WindowInteropHelper(this)).Handle;
                WinInterop.HwndSource.FromHwnd(handle).AddHook(new WinInterop.HwndSourceHook(WindowProc));
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

        }



        private void DragableGridMouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                    DragMove();

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

        }

        private childItem FindVisualChild<childItem>(DependencyObject obj)
                where childItem : DependencyObject
        {
            try
            {

                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                    if (child != null && child is childItem)
                        return (childItem)child;
                    else
                    {
                        childItem childOfChild = FindVisualChild<childItem>(child);
                        if (childOfChild != null)
                            return childOfChild;
                    }
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

            return null;

        }

        private void btnStartCheck_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (isRunning)
                {
                    //TODO:AG call start worker
                    worker.Cancel();
                }
                else
                {
                    worker.Start();
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

        public void worker_ProgressUpdate(string Task, decimal Status)
        {
            try
            {
                var bc = new BrushConverter();
                statusBar.Foreground = (Brush)bc.ConvertFrom("#003366");
              
                this.statusText.Text = "Collecting Data from " + Task;
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

        }


        
        private void worker_Completed(object sender, EventArgs e)
        {
            try
            {
                var bc = new BrushConverter();
                statusBar.Foreground = (Brush)bc.ConvertFrom("#003366");
                statusText.Text = "Preparing to Optimize...";
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
        private void worker_Cancelled(object sender, EventArgs e)
        {
            // ResetUI();
            statusText.Text = "Work cancelled.";
        }
        private void WorkFailed(object sender, EventArgs e)
        {
            //ResetUI();
            statusText.Text = "Work FAILED!";
        }

        public void worker_ProccessCompleted()
        {
            try
            {

                string imageUri = "pack://application:,,,/SharePointOptimizer.PL.WPF;component/Images/start.png";
                var button = this.btnStartCheck as Button;
                button.ToolTip = "Start Scan";
                Image _imgrestor_down = (Image)button.FindName("image_start");
                if (_imgrestor_down == null)
                    return;

                _imgrestor_down.Source = new ImageSourceConverter().ConvertFromString(imageUri) as ImageSource;
                var bc = new BrushConverter();
                statusBar.Foreground = (Brush)bc.ConvertFrom("#003366");
                statusText.Text = "SharePoint Optimization Completed Successfully...";

                // showIssues();

                Storyboard translationAnimationStoryboard = (Storyboard)this.Resources["TabStoryboardResource"];
                translationAnimationStoryboard.Seek(this, new TimeSpan(0, 0, 0), TimeSeekOrigin.BeginTime);
                translationAnimationStoryboard.Begin(this, true);

                tabMain.SelectedIndex = 1;
                IssueReport.RefreshReport();

                this.Cursor = Cursors.Arrow;


            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
            finally
            {
                isRunning = false;


            }

        }


        public void HelpExecuted(object sender, ExecutedRoutedEventArgs e)
        {

            System.Diagnostics.Process.Start("http://www.SharePointOptimizer.com/support/");

        }

        public void HelpCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }


        private void btnAdvanceOptions_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OptionDialog dialog = new OptionDialog(this);
                if (dialog.ShowDialog() == true)
                {

                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }


        //TODO: AG 
       
        private void rvDatabaseandFiles_Load(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }


        private void btnClose_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Close();
        }

        private void btnMaximizeWindow_Click(object sender, System.Windows.RoutedEventArgs e)
        {

        }

        private void btnChangeView_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                //This Button event changes the restore down and maximize image in the buttons.

                if (this.WindowState == WindowState.Maximized)
                {
                    string imageUri = "pack://application:,,,/SharePointOptimizer.PL.WPF;component/Images/maximize.png";

                    WindowState = WindowState.Normal;

                    var button = sender as Button;

                    button.ToolTip = "Maximize";

                    Image _imgrestor_down = (Image)button.FindName("restore_down");

                    _imgrestor_down.Source = new ImageSourceConverter().ConvertFromString(imageUri) as ImageSource;


                }
                else
                {
                    string imageUri2 = "pack://application:,,,/SharePointOptimizer.PL.WPF;component/Images/change.png";

                    WindowState = WindowState.Maximized;

                    var button = sender as Button;

                    button.ToolTip = "Restore Down";

                    Image _imgrestor_down = (Image)button.FindName("restore_down");

                    _imgrestor_down.Source = new ImageSourceConverter().ConvertFromString(imageUri2) as ImageSource;



                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

        private void btnMinimizeWindow_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }
        private static System.IntPtr WindowProc(
      System.IntPtr hwnd,
      int msg,
      System.IntPtr wParam,
      System.IntPtr lParam,
      ref bool handled)
        {

            switch (msg)
            {
                case 0x0024:
                    WmGetMinMaxInfo(hwnd, lParam);
                    handled = true;
                    break;
            }

            return (System.IntPtr)0;
        }

        private static void WmGetMinMaxInfo(System.IntPtr hwnd, System.IntPtr lParam)
        {
            try
            {
                MINMAXINFO mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));

                // Adjust the maximized size and position to fit the work area of the correct monitor
                int MONITOR_DEFAULTTONEAREST = 0x00000002;
                System.IntPtr monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);

                if (monitor != System.IntPtr.Zero)
                {

                    MONITORINFO monitorInfo = new MONITORINFO();
                    GetMonitorInfo(monitor, monitorInfo);
                    RECT rcWorkArea = monitorInfo.rcWork;
                    RECT rcMonitorArea = monitorInfo.rcMonitor;
                    mmi.ptMaxPosition.x = Math.Abs(rcWorkArea.left - rcMonitorArea.left);
                    mmi.ptMaxPosition.y = Math.Abs(rcWorkArea.top - rcMonitorArea.top);
                    mmi.ptMaxSize.x = Math.Abs(rcWorkArea.right - rcWorkArea.left);
                    mmi.ptMaxSize.y = Math.Abs(rcWorkArea.bottom - rcWorkArea.top);
                }

                Marshal.StructureToPtr(mmi, lParam, true);

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }


        /// <summary>
        /// POINT aka POINTAPI
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            /// <summary>
            /// x coordinate of point.
            /// </summary>
            public int x;
            /// <summary>
            /// y coordinate of point.
            /// </summary>
            public int y;

            /// <summary>
            /// Construct a point of coordinates (x,y).
            /// </summary>
            public POINT(int x, int y)
            {
                this.x = x;
                this.y = y;
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MINMAXINFO
        {
            public POINT ptReserved;
            public POINT ptMaxSize;
            public POINT ptMaxPosition;
            public POINT ptMinTrackSize;
            public POINT ptMaxTrackSize;
        };

        void win_Loaded(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Maximized;
        }


        /// <summary>
        /// </summary>
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public class MONITORINFO
        {
            /// <summary>
            /// </summary>            
            public int cbSize = Marshal.SizeOf(typeof(MONITORINFO));

            /// <summary>
            /// </summary>            
            public RECT rcMonitor = new RECT();

            /// <summary>
            /// </summary>            
            public RECT rcWork = new RECT();

            /// <summary>
            /// </summary>            
            public int dwFlags = 0;
        }


        /// <summary> Win32 </summary>
        [StructLayout(LayoutKind.Sequential, Pack = 0)]
        public struct RECT
        {
            /// <summary> Win32 </summary>
            public int left;
            /// <summary> Win32 </summary>
            public int top;
            /// <summary> Win32 </summary>
            public int right;
            /// <summary> Win32 </summary>
            public int bottom;

            /// <summary> Win32 </summary>
            public static readonly RECT Empty = new RECT();

            /// <summary> Win32 </summary>
            public int Width
            {
                get { return Math.Abs(right - left); }  // Abs needed for BIDI OS
            }
            /// <summary> Win32 </summary>
            public int Height
            {
                get { return bottom - top; }
            }

            /// <summary> Win32 </summary>
            public RECT(int left, int top, int right, int bottom)
            {
                this.left = left;
                this.top = top;
                this.right = right;
                this.bottom = bottom;
            }


            /// <summary> Win32 </summary>
            public RECT(RECT rcSrc)
            {
                this.left = rcSrc.left;
                this.top = rcSrc.top;
                this.right = rcSrc.right;
                this.bottom = rcSrc.bottom;
            }

            /// <summary> Win32 </summary>
            public bool IsEmpty
            {
                get
                {
                    // BUGBUG : On Bidi OS (hebrew arabic) left > right
                    return left >= right || top >= bottom;
                }
            }
            /// <summary> Return a user friendly representation of this struct </summary>
            public override string ToString()
            {
                if (this == RECT.Empty) { return "RECT {Empty}"; }
                return "RECT { left : " + left + " / top : " + top + " / right : " + right + " / bottom : " + bottom + " }";
            }

            /// <summary> Determine if 2 RECT are equal (deep compare) </summary>
            public override bool Equals(object obj)
            {
                if (!(obj is Rect)) { return false; }
                return (this == (RECT)obj);
            }

            /// <summary>Return the HashCode for this struct (not garanteed to be unique)</summary>
            public override int GetHashCode()
            {
                return left.GetHashCode() + top.GetHashCode() + right.GetHashCode() + bottom.GetHashCode();
            }


            /// <summary> Determine if 2 RECT are equal (deep compare)</summary>
            public static bool operator ==(RECT rect1, RECT rect2)
            {
                return (rect1.left == rect2.left && rect1.top == rect2.top && rect1.right == rect2.right && rect1.bottom == rect2.bottom);
            }

            /// <summary> Determine if 2 RECT are different(deep compare)</summary>
            public static bool operator !=(RECT rect1, RECT rect2)
            {
                return !(rect1 == rect2);
            }


        }

        [DllImport("user32")]
        internal static extern bool GetMonitorInfo(IntPtr hMonitor, MONITORINFO lpmi);

        /// <summary>
        /// 
        /// </summary>
        [DllImport("User32")]
        internal static extern IntPtr MonitorFromWindow(IntPtr handle, int flags);

        private void Window_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

        }



        private void btnSaveResults_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                SaveFileDialog saveDatabasebackup = new SaveFileDialog();
                saveDatabasebackup.Filter = "Database Backup|*.bak";
                saveDatabasebackup.Title = "Save a Database Snap Shot";
                saveDatabasebackup.ShowDialog();

                if (saveDatabasebackup.FileName != "")
                {


                    try { BackupRestore.BackupDatabase(saveDatabasebackup.FileName); }

                    catch (Exception ex)
                    {



                    }
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

        }

        private void btnRestore_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {

                OpenFileDialog openFileDialog1 = new OpenFileDialog();

                openFileDialog1.InitialDirectory = "c:\\";
                openFileDialog1.Filter = "bak Files (*.bak)|*.bak|All Files (*.*)|*.*";
                openFileDialog1.FilterIndex = 2;
                openFileDialog1.RestoreDirectory = true;

                if (openFileDialog1.ShowDialog().HasValue)
                {
                    if (!String.IsNullOrEmpty(openFileDialog1.FileName))
                    {
                        try
                        {

                            BackupRestore.RestoreDatabase(openFileDialog1.FileName);


                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Error: Could not read File from disk. Original error: " + ex.Message);
                            Logger.Error(ex);
                        }


                        finally
                        {
                            IssueReport.RefreshReport();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }

        private void image_start_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }

        private void IssueReport_Loaded(object sender, RoutedEventArgs e)
        {

        }




    }
}

